package org.libraq.org.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import javafx.scene.shape.VLineTo;
import org.libraq.basic.util.AjaxResult;
import org.libraq.basic.util.PageList;
import org.libraq.org.domain.Department;
import org.libraq.org.query.DepartmentQuery;
import org.libraq.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/department")
@Api(value = "/department",description = "前端数据接口，后端控制器")
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;

    @GetMapping
    public List<Department> getAll(){
        return departmentService.findAll();
    }

    @GetMapping("/{id}")
    public Department getById(@PathVariable("id") Long id){
        return departmentService.findById(id);
    }

    @PostMapping
    public PageList<Department> getByQuery(@RequestBody DepartmentQuery query){
        return departmentService.findByQuery(query);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除",notes = "通过id删除")
    public AjaxResult delete(@PathVariable("id") @ApiParam("主键id") Long id){
        try {
            departmentService.delete(id);
            return AjaxResult.me().setMsg("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            //静态方法+链式编程 酷帅
            return AjaxResult.me().setMsg("删除失败"+e.getMessage());
        }
    }

    @PutMapping
    public AjaxResult save(@RequestBody Department department){
        //在数据接口出判断是否接收到id
        try {
            if(department.getId()==null){
                departmentService.save(department);
                return AjaxResult.me().setMsg("添加成功");
            }else {
                departmentService.update(department);
                return AjaxResult.me().setMsg("修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMsg("操作失败"+e.getMessage());
        }
    }

    @PatchMapping
    public AjaxResult patchDel(@RequestBody List<Long> ids){
        try {
            departmentService.patchDel(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("批量删除失败");
        }
    }

    @GetMapping("/tree")
    public List<Department> getDeptTree(){
         return departmentService.getDeptTree();
    }


}
